Page({
  data: {
    categories: [
      { id: 0, name: '全部' },
      { id: 1, name: '前端开发' },
      { id: 2, name: '后端开发' },
      { id: 3, name: '移动开发' },
      { id: 4, name: '数据科学' },
      { id: 5, name: '产品设计' },
      { id: 6, name: '运维测试' },
      { id: 7, name: '人工智能' }
    ],
    currentCategory: 0,
    currentSort: 'default',
    sortOrder: 'desc',
    courses: [],
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,
    isRefreshing: false
  },

  onLoad(options) {
    if (options.categoryId) {
      this.setData({
        currentCategory: parseInt(options.categoryId)
      })
    }
    this.loadCourseList()
  },

  // 切换分类
  onCategoryChange(e) {
    const categoryId = e.currentTarget.dataset.id
    this.setData({
      currentCategory: categoryId,
      courses: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadCourseList()
  },

  // 切换排序
  onSortChange(e) {
    const sortType = e.currentTarget.dataset.type
    let sortOrder = this.data.sortOrder

    if (this.data.currentSort === sortType) {
      sortOrder = sortOrder === 'desc' ? 'asc' : 'desc'
    } else {
      sortOrder = 'desc'
    }

    this.setData({
      currentSort: sortType,
      sortOrder: sortOrder,
      courses: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadCourseList()
  },

  // 加载课程列表
  loadCourseList() {
    if (this.data.isLoading || !this.data.hasMore) return

    this.setData({ isLoading: true })

    // TODO: 调用课程列表API
    // 模拟API调用
    setTimeout(() => {
      const mockData = [
        {
          id: 1,
          title: 'Vue.js 3.0 从入门到精通',
          description: '从基础到实战，全面掌握Vue3新特性和开发技巧',
          coverUrl: '/assets/images/course/vue3.png',
          teacherName: '张老师',
          price: 299,
          studentCount: 1234
        },
        {
          id: 2,
          title: 'React Native实战教程',
          description: '使用React Native开发原生移动应用，一次编写，多端运行',
          coverUrl: '/assets/images/course/react-native.png',
          teacherName: '李老师',
          price: 399,
          studentCount: 888
        }
      ]

      this.setData({
        courses: this.data.pageNum === 1 ? mockData : this.data.courses.concat(mockData),
        isLoading: false,
        hasMore: this.data.pageNum < 3, // 模拟数据只有3页
        pageNum: this.data.pageNum + 1,
        isRefreshing: false
      })
    }, 1000)
  },

  // 下拉刷新
  onRefresh() {
    this.setData({
      isRefreshing: true,
      courses: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadCourseList()
  },

  // 上拉加载更多
  onLoadMore() {
    this.loadCourseList()
  },

  // 跳转到课程详情
  onCourseTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/course/detail?id=${id}`
    })
  }
})